import { Directive, DirectiveBinding } from "vue";

/**
 * v-copy
 * 复制某个值至剪贴板
 * 接收参数：string类型/Ref<string>类型/Reactive<string>类型
 */
interface ElType extends HTMLElement {
    copyData: string | number;
    __handleClick__: any;
}

const copy: Directive = {
    mounted(el: ElType, binding: DirectiveBinding) {
        el.copyData = binding.value;
        el.addEventListener("click", handleClick);
    },
    updated(el: ElType, binding: DirectiveBinding) {
        el.copyData = binding.value;
    },
    beforeUnmount(el: ElType) {
        el.removeEventListener("click", el.__handleClick__);
    }
}

async function handleClick(this: any) {
    if (!this.copyData) {
        ElMessage({ message: "Nothing to copy!", type: "warning" })
        return
    };
    if (navigator.clipboard && window.isSecureContext) {
        await navigator.clipboard
            .writeText(this.copyData)
            .then(() => {
                ElMessage({ message: "复制成功!", type: "success" });
            })
            .catch(() => {
                ElMessage({ message: "复制操作不被支持或失败!", type: "error" });
            });
    } else {
        let textarea = document.createElement("textarea");
        textarea.readOnly = true;
        textarea.style.position = "absolute";
        textarea.style.left = "-9999px";
        textarea.value = this.copyData;
        document.body.appendChild(textarea);
        textarea.select();
        const result = document.execCommand("Copy");
        if (result) ElMessage({ message: "复制成功!", type: "success" });
        else ElMessage({ message: "复制操作不被支持或失败!", type: "error" });
        document.body.removeChild(textarea);
    }
}

export default copy;